<template>
  <div>
    <el-card class="app-container" v-loading="loading" style="min-height: 500px">
      <!--      <div slot="header" class="clearfix">-->
      <!--        <span>发布新商品</span>-->
      <!--      </div>-->
      <div v-if="detail">
        <div class="flex cat">
          <div>商品分类</div>
          <div class="cat__items flex">
            <div v-for="(c,idx) in detail.catNames" :key="idx" class="cat__item">{{ c }}</div>
          </div>
        </div>
        <el-form ref="form" :model="formData" :rules="formRules" label-position="right" label-width="120px" size="mini">
          <div class="box">
            <div class="flex box__title">
              <span>1</span>
              基础信息
            </div>
            <div class="box__content">
              <el-form-item label="商品轮播图" required prop="bannerImgList">
                <el-alert
                  style="line-height: 1.3;padding: 10px 0"
                  :closable="false"
                  type="warning"
                  title="图片要求"
                >
                  宽高比例为1:1或3:4，且宽高均大于480px，大小1M内。已上传{{ formData.bannerImgList.length }}/10张，拖拽可调整顺序
                </el-alert>
                <div class="pt10">
                  <sortable-upload v-model="formData.bannerImgList" :limit="10"/>
                </div>
              </el-form-item>
              <el-form-item label="商品标题" required prop="title">
                <el-input v-model="formData.title" placeholder="商品标题组成：商品描述+规格，最多输入30个汉字（60个字符）"/>
              </el-form-item>

              <el-form-item v-if="detail.propList.values.length" label="商品属性">
                <div class="spu__propList">
                  <div class="border-b spu__propListTitleArea">
                    <div>
                      属性填写率 {{ detail.propList.skuPropWriteRates }}%
                    </div>
                    <div>
                      请准确填写属性，有利于商品在搜索和推荐中露出，错误填写可能面临商品下架或流量损失！(注：
                      <i
                        class="el-icon-star-on important-color"
                      />带为重要属性)。
                    </div>
                  </div>
                  <div class="spu__propListContent">
                    <el-row :gutter="20">
                      <el-col v-for="(p,idx) in detail.propList.values" :key="idx" :span="12">
                        <el-form-item :required="p.isRequired">
                          <span slot="label"> <i
                            v-if="p.isImportant"
                            class="el-icon-star-on important-color"
                          />{{ p.title }}</span>
                          <el-select v-model="p.value" filterable clearable>
                            <el-option v-for="v in p.valueList" :key="v.value" :value="v.value" :label="v.value"/>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="商品视频" prop="videoSrc">
                <el-alert
                  style="line-height: 1.3;padding: 10px 0"
                  :closable="false"
                  type="warning"
                  title="视频要求"
                >
                  时长60秒以内；宽高比为1:1或16:9或3:4。添加后展示在商详头图位置，以提高商品转化率
                </el-alert>
                <div class="pt10">
                  <sortable-upload v-model="formData.videoSrc" is-single :limit="1"/>
                </div>
              </el-form-item>
              <el-form-item label="商详视频" prop="detailVideoSrc">
                <el-alert
                  style="line-height: 1.3;padding: 10px 0"
                  :closable="false"
                  type="warning"
                  title="视频要求"
                >
                  时长3分钟以内；宽高比为16:9。上传后展示在商详图文详情顶部
                </el-alert>
                <div class="pt10">
                  <sortable-upload v-model="formData.detailVideoSrc" is-single :limit="1"/>
                </div>
              </el-form-item>
              <el-form-item label="商品详情" prop="detailImgList">
                <div class="tip"> 详情介绍商品以提升转化。若未编辑，商品发布后轮播图将自动填充至图文详情</div>
                <div class="pt10">
                  <sortable-upload v-model="formData.detailImgList" :limit="50"/>
                </div>
              </el-form-item>
            </div>
          </div>
          <div class="box">
            <div class="flex box__title">
              <span>2</span>
              规格与库存
            </div>
            <div class="box__content">
              <el-form-item label="商品规格" :required="!detail.salePropList.canAddProperty">
                <div class="spu__salePropList">
                  <div v-if="detail.salePropList.canAddProperty" class="tip">最多添加两个商品规格类型，第一个商品规格类型可添加规格图片</div>
                  <div v-for="(s,sIdx) in detail.salePropList.values" :key="sIdx" class="spu__salePropGroup">
                    <div
                      v-if="s.selectable"
                      class="flex spu__salePropGroupTitleWrap"
                      style="border-bottom: 1px solid #eee;padding-bottom: 10px"
                    >
                      <div class="flex-con spu__salePropGroupTitle flex">
                        <el-select
                          v-model="s.title"
                          :placeholder="'规格类型'+(sIdx+1)"
                          @change="handleChangePropertyOption(sIdx)"
                        >
                          <el-option
                            v-for="o in detail.salePropList.propertyOptions(sIdx)"
                            :key="o.id"
                            :label="o.title"
                            :value="o.title"
                          />
                        </el-select>
                        <el-checkbox v-if="s.uploadPicFlag" v-model="s.isUploadPic" style="margin-left: 20px">添加图片
                        </el-checkbox>
                      </div>
                      <div v-if="s.deletable" class="spu__salePropGroupTitleTip">
                        <el-button type="text" @click="handleRemoveProperty(sIdx)">删除规格类型</el-button>
                      </div>
                    </div>
                    <div v-else class="flex spu__salePropGroupTitleWrap">
                      <div class="spu__salePropGroupTitle">
                        {{ s.title }}
                      </div>
                      <div class="spu__salePropGroupTitleTip">
                        {{ s.bottomTip }}
                      </div>
                    </div>
                    <div v-if="s.isSelectInput">
                      <div v-if="s.isValueGrouped" class="flex spu__tabs">
                        <div
                          v-for="g in s.groupList"
                          :key="g.id"
                          class="spu__tab"
                          :class="{'spu__tab--selected':s.selectedGroup === g.id}"
                          @click="handleToggleGroupTab(s,g)"
                        >
                          {{ g.title }}
                        </div>
                      </div>
                      <div class="spu__salePropListItems">
                        <el-row :gutter="20">
                          <el-col v-for="v in s.valueList[s.selectedGroup]" :key="v.id" :span="8">
                            <div class="flex spu__salePropListItem">
                              <div class="rel">
                                <el-checkbox v-model="v.checked">
                                  {{ v.isSelfEdit ? '' : v.value }}
                                </el-checkbox>
                                <div class="checkbox-master" @click="handleToggleSkuChecked(v)"/>
                              </div>

                              <el-input
                                v-if="v.isSelfEdit"
                                v-model="v.value"
                                :placeholder="'自定义'+ s.title"
                                clearable
                                class="spu__selfProp"
                                @blur="handleBlurValue(s,v,v)"
                              >
                                <span slot="append" v-if="s.valueUnit">{{ s.valueUnit }}</span>
                              </el-input>
                              <el-input v-if="v.checked && s.canNoteFlag" v-model="v.notes" class="spu__propNotes"
                                        placeholder="备注"/>
                            </div>
                          </el-col>
                        </el-row>
                      </div>
                    </div>
                    <div v-if="s.isDialogInput">
                      <el-row :gutter="20" class="pt10 mb-10">
                        <el-col v-for="v in s.valueList[s.selectedGroup]" :key="v._key" :span="12" class="pb20">
                          <div class="flex space-between">
                            <dialog-selector
                              class="spu__color"
                              :value="v.value"
                              :before-change="handleCheckValue.bind(this,s)"
                              :options="s.sourceValueList"
                              placeholder="选择或输入主色"
                              @blur="handleBlurValue(s,v,$event)"
                            />
                            <el-input v-if="v.value" v-model="v.notes" class="spu__color" placeholder="备注（偏深/浅等）"/>
                            <sortable-upload v-if="v.value" v-model="v.previewImg" @input="handleChangePic" is-single
                                             width="30" height="30"/>
                            <el-button v-if="v.value" type="text" @click="handleRemoveValue(s,v)">删除</el-button>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                    <div v-else-if="s.selectable && s.title" style="padding-top: 10px">
                      <el-row :gutter="20">
                        <el-col v-for="v in s.valueList[s.selectedGroup]" :key="v.id" :span="8">
                          <div class="flex spu__salePropListItem space-between">
                            <el-input
                              v-if="v.isSelfEdit"
                              v-model="v.value"
                              placeholder="请输入规格名称"
                              clearable
                              style="width: 160px"
                              class="spu__selfProp"
                              @blur="handleBlurValue(s,v,v)"
                            />
                            <sortable-upload
                              v-if="v.value && s.isUploadPic"
                              v-model="v.previewImg"
                              is-single
                              width="30"
                              height="30"
                            />
                            <el-button v-if="v.value" type="text" @click="handleRemoveValue(s,v)">删除</el-button>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                  <div v-if="detail.salePropList.canAddProperty" style="margin-top: 10px">
                    <el-button icon="el-icon-plus" type="default" @click="handleAddProperty">添加规格类型</el-button>
                  </div>
                </div>
              </el-form-item>
            </div>
            <div class="box__content">
              <el-form-item label="价格与库存" required>
                <div class="spu__salePropList">
                  <el-alert
                    style="line-height: 1.3;padding: 10px 0"
                    :closable="false"
                    type="warning"
                    title="提示"
                  >
                    请如实填写库存信息，以确保商品可以在承诺发货时间内发出，避免可能的物流违规
                  </el-alert>
                  <div v-if="!detail.salePropList.isSingleSku" class="batch pt10 space-between flex">
                    <el-select
                      v-for="o in detail.salePropList.batchOptions"
                      :key="o.title"
                      v-model="o.value"
                      style="width: 120px"
                      :placeholder="'请选择'+o.title"
                    >
                      <el-option :label="o.title" value="0"/>
                      <el-option v-for="v in o.options" :key="v.id" :value="v.id" :label="v.value"/>
                    </el-select>
                    <el-input
                      v-if="!isEditMode"
                      @keydown.native="SkuUtil.handleLimitInteger"
                      v-model="detail.salePropList.batchStock"
                      placeholder="库存"
                      style="width: 120px"
                    />
                    <div v-if="isEditMode" class="rel">
                      <div class="delta-stock-flag">
                        <div
                          class="delta-stock-flag__item"
                          :class="{'delta-stock-flag__item--selected':detail.salePropList.isBatchAddStock}"
                          @click="detail.salePropList.isBatchAddStock=true"
                        >增
                        </div>
                        <div
                          class="delta-stock-flag__item"
                          :class="{'delta-stock-flag__item--selected':!detail.salePropList.isBatchAddStock}"
                          @click="detail.salePropList.isBatchAddStock=false"
                        >减
                        </div>
                      </div>
                      <el-input
                        v-model="detail.salePropList.batchStock"
                        @keydown.native="SkuUtil.handleLimitInteger"
                        class="delta-stock"
                        placeholder="库存"
                        style="width: 120px"
                      />
                    </div>
                    <el-input v-model="detail.salePropList.batchPrice" placeholder="价格" style="width: 120px"
                              @keydown.native="SkuUtil.handleLimitFloat"
                              @blur="SkuUtil.handleLimitFloatPrecision($event,2)"
                    >
                      <div slot="suffix">元</div>
                    </el-input>
                    <el-button
                      style="width: 80px"
                      type="primary"
                      :disabled="!detail.salePropList.canBatchSet"
                      @click="handleBatchSet"
                    >批量设置
                    </el-button>
                  </div>
                  <div class="pt10">
                    <table class="spu__prop-table">
                      <thead>
                      <tr>
                        <th v-for="t in detail.salePropList.checkedPropTitleList" :key="t">{{ t }}</th>
                        <th v-if="isEditMode" class="spu__prop-value" style="width: 120px">当前库存</th>
                        <th v-if="isEditMode" class="spu__prop-value--required" style="width: 140px">库存增减</th>
                        <th v-if="isEditMode" class="spu__prop-value" style="width: 120px">改后库存</th>
                        <th v-else class="spu__prop-value--required" style="width: 120px">库存</th>
                        <th class="spu__prop-value--required" style="width: 140px">价格(元)</th>
                        <th
                          v-if="!detail.salePropList.isSingleSku"
                          class="spu__prop-value--required"
                          style="width: 80px"
                        >
                          预览图
                        </th>
                        <th style="width: 200px" class="spu__prop-value">规格编码</th>
                        <th v-if="detail.salePropList.isSingleSku" style="width: 200px" class="spu__prop-value">商品编码
                        </th>
                      </tr>
                      </thead>
                      <tbody>
                      <tr v-for="sku in detail.salePropList.skuList.values" :key="sku._key">
                        <template v-for="v in sku.values">
                          <td v-if="v.rowSpan" :key="v.id" :rowspan="v.rowSpan">
                            {{ v.value }}
                          </td>
                        </template>
                        <td v-if="isEditMode" class="spu__prop-value" style="width: 120px">{{ sku.stock }}</td>
                        <td v-if="isEditMode">
                          <div class="delta-stock-td">
                            <div class="delta-stock-flag">
                              <div
                                class="delta-stock-flag__item"
                                :class="{'delta-stock-flag__item--selected':sku.isAddStock}"
                                @click="handleToggleAddStockFlag(sku,true)"
                              >增
                              </div>
                              <div
                                class="delta-stock-flag__item"
                                :class="{'delta-stock-flag__item--selected':!sku.isAddStock}"
                                @click="handleToggleAddStockFlag(sku,false)"
                              >减
                              </div>
                            </div>
                            <el-input
                              v-model="sku.deltaStock"
                              class="delta-stock"
                              :controls="false"
                              @keydown.native="SkuUtil.handleLimitInteger"
                              style="width: 120px"
                              placeholder="请输入"
                              @input="handleChangeDeltaStock(sku)"
                            />
                          </div>

                        </td>
                        <td v-if="isEditMode">
                          <el-input
                            v-model="sku.finalStock"
                            :precision="0"
                            @keydown.native="SkuUtil.handleLimitInteger"
                            :controls="false"
                            style="width: 90px"
                            placeholder="请输入"
                            @input="handleChangeFinalStock(sku)"
                          />
                        </td>
                        <td v-else>
                          <el-input
                            v-model="sku.stock"
                            :precision="0"
                            @keydown.native="SkuUtil.handleLimitInteger"
                            :controls="false"
                            style="width: 90px"
                            placeholder="请输入"
                          />
                        </td>
                        <td>
                          <el-input
                            v-model="sku.price"
                            :controls="false"
                            @keydown.native="SkuUtil.handleLimitFloat"
                            @blur="SkuUtil.handleLimitFloatPrecision($event,2)"
                            placeholder="请输入"
                            @change="handleChangePrice"
                            style="width: 110px"
                          />
                        </td>
                        <td v-if="!detail.salePropList.isSingleSku">
                          <sortable-upload v-model="sku.previewImg" is-single width="40" height="40"/>
                        </td>
                        <td>
                          <el-input v-model="sku.skuNo" placeholder="请输入" style="width: 160px"/>
                        </td>
                        <td v-if="detail.salePropList.isSingleSku">
                          <el-input v-model="formData.spuNo" placeholder="请输入" style="width: 160px"/>
                        </td>
                      </tr>
                      </tbody>
                    </table>
                    <div v-if="!detail.salePropList.isSingleSku" class="flex summary">
                      <div class="flex flex-con">
                        <div class="flex summary__item">
                          <div class="summary__label">总库存</div>
                          <div class="summary__value">{{ detail.salePropList.skuList.totalStock || '系统自动计算' }}</div>
                        </div>
                        <div class="flex summary__item">
                          <div class="summary__label">价格</div>
                          <div class="summary__value">{{ detail.salePropList.skuList.price || 0 }} 元</div>
                        </div>
                      </div>
                      <div class="flex summary__item">
                        <div class="summary__label">
                          商品编码
                        </div>
                        <el-input
                          v-model="formData.spuNo"
                          class="summary__input"
                          placeholder="请输入"
                          style="width: 200px"
                        />
                      </div>
                    </div>
                  </div>
                  <div class="sku_errmsg">
                    {{ skuErrMsg }}
                  </div>

                </div>
              </el-form-item>
            </div>
            <div class="box__content">
              <el-form-item label="市场价" required prop="marketPrice">
                <el-input v-model="formData.marketPrice" placeholder="应高于商品最大购买价" style="width: 220px"
                          @change="handleChangeMarketPrice">
                  <div slot="append">元</div>
                </el-input>
              </el-form-item>
            </div>
          </div>
          <div class="box">
            <div class="flex box__title">
              <span>3</span>
              服务与承诺
            </div>
            <div class="box__content">
              <el-form-item label="运费模板" required>
                <el-radio-group v-model="freightTemplateType" @change="handleChangeFreightTemplateType">
                  <el-radio v-for="s in freightTemplateTypeList" :key="s.id" :label="s.id">
                    {{ s.title }}
                  </el-radio>
                </el-radio-group>
                <div class="flex pt10 space-between" v-if="freightTemplateType===1">
                  <el-select v-model="formData.freightTemplateId" placeholder="运费模板"
                             style="width: 200px">
                    <el-option v-for="i in freightTemplateOptions" :value="i.id" :key="i.id" :label="i.title"/>
                  </el-select>
                  <!--                  <el-button @click="handleToCreateNewFreightTemplate" type="text">新建运费模板</el-button>-->
                  <el-link href="/#/oms/freight-template/add" target="_blank"
                           @click.native="handleToCreateNewFreightTemplate"
                           type="primary">新建运费模板
                  </el-link>
                </div>
              </el-form-item>
              <el-form-item label="承诺" required prop="serviceIdList">
                <el-checkbox-group v-model="formData.serviceIdList">
                  <div v-for="s in serviceList" :key="s.id">
                    <el-checkbox :label="s.id">{{ s.title }}</el-checkbox>
                  </div>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </div>
        </el-form>
      </div>

    </el-card>
    <div class="btn-area-holder"/>
    <div class="btn-area btn-area--fixed text-center">
      <el-button v-if="!isEditMode" type="primary" size="small" :loading="isSubmitting" @click="handleSubmit">提交并上架
      </el-button>
      <el-button v-else type="primary" size="small" :loading="isSubmitting" @click="handleSubmitUpdateSpu">提交
      </el-button>
    </div>
  </div>

</template>

<script>
import {categoryApi} from '@/feature/pdt/infra/api/categoryApi'
import SortableUpload from '@/framework/components/SortableUpload'
import DialogSelector from '@/framework/components/DialogSelector'
import {propertyApi} from '@/feature/pdt/infra/api/propertyApi'
import SkuEntityCollection from '@/feature/pdt/domain/SkuEntityCollection'
import {spuApi} from '@/feature/pdt/infra/api/spuApi'
import {freightTemplateApi} from '@/feature/pdt/infra/api/freightTemplateApi'
import SpuConvertor from '@/feature/pdt/convertor/SpuConvertor'
import FormUtil from '@/framework/infra/form/FormUtil'
import CollectionUtil from "@/framework/infra/collection/CollectionUtil";
import SkuUtil from "@/framework/components/sku/SkuUtil";

export default {
  components: {DialogSelector, SortableUpload},
  data() {
    return {
      isEditMode: false,
      detail: null,
      skuErrMsg: '',
      isSubmitting: false,
      SkuUtil,
      loading: true,
      formData: {
        title: '',
        detailVideoSrc: '',
        videoSrc: '',
        detailImgList: [],
        bannerImgList: [],
        marketPrice: '',
        serviceIdList: [],
        freightTemplateId: '1',
        spuNo: ''
      },
      serviceList: [],
      // 模板ID类型
      freightTemplateType: 0,
      freightTemplateTypeList: [{
        id: 0,
        title: '默认模板'
      }, {
        id: 1,
        title: '其他模板'
      }],
      freightTemplateOptions: [],
      skuList: new SkuEntityCollection(),
      formRules: {
        title: [
          {
            required: true,
            message: '商品标题不能为空'
          }
        ],
        freightTemplateId: [
          {
            required: true,
            message: '请选择运费模板'
          }
        ],
        marketPrice: [
          {
            required: true,
            message: '市场价不能为空'
          }
        ],
        bannerImgList: [
          {
            required: true,
            type: 'array',
            message: '请上传商品轮播图'
          }
        ],
        serviceIdList: [
          {
            required: true,
            type: 'array',
            message: '请选择至少一个承诺'
          }
        ]
      }
    }
  },
  // watch: {
  //   'detail.salePropList.values': {
  //     deep: true,
  //     handler() {
  //       if (!this.detail || !this.detail.salePropList) {
  //         return
  //       }
  //       this.detail.salePropList.onCheckedPropValueChanged()
  //     }
  //   }
  // },
  created() {
    this.isEditMode = !!(this.$route.query.id && !this.$route.query.categoryId)
    if (this.isEditMode) { // 编辑模式
      spuApi.detail(this.$route.query.id).then(data => {
        FormUtil.fill(this.formData, data)
        this.detail = data
        this.loadFreightTemplates().then(data => {
          if (this.freightTemplateOptions.length > 0) {
            if (!this.formData.freightTemplateId) {
              this.formData.freightTemplateId = this.freightTemplateOptions[this.freightTemplateOptions.length - 1].id
            } else {
              this.freightTemplateType = this.freightTemplateOptions[this.freightTemplateOptions.length - 1].id === this.formData.freightTemplateId ? 0 : 1
            }
          }
        })
        this.detail.salePropList.onCheckedPropValueChanged()
      }).finally(() => {
        this.loading = false
      })
    } else {
      categoryApi.detail(this.$route.query.categoryId).then(data => {
        this.detail = data
        this.loadFreightTemplates()
      }).finally(() => {
        this.loading = false
      })
    }
    spuApi.querySpuServiceList().then(data => {
      this.serviceList = data
    })
  },
  methods: {
    handleToCreateNewFreightTemplate() {
      this.$confirm('请确认您已完成运费模板新建', '确认').then(() => {
        this.loadFreightTemplates()
      })
    },
    handleChangeFreightTemplateType() {
      if(this.freightTemplateType === 0) {
        this.formData.freightTemplateId = '1'
      }
    },
    loadFreightTemplates() {
      return freightTemplateApi.list().then(data => {
        this.freightTemplateOptions = data
      })
    },
    handleChangePrice() {
      this.formData.marketPrice = Math.max(this.detail.salePropList.skuList.maxSkuPrice() + 1, this.formData.marketPrice || 0)
      this.skuErrMsg = ''
    },
    handleChangeMarketPrice() {
      if (this.formData.marketPrice === '') {
        this.skuErrMsg = ''
        return
      }
      try {
        // 校验
        this.detail.salePropList.skuList.assertMaxPriceLessThan(this.formData.marketPrice)
        this.skuErrMsg = ''
      } catch (ex) {
        this.skuErrMsg = ex.message
      }
    },
    handleToggleAddStockFlag(sku, isAddStock) {
      sku.isAddStock = isAddStock
      sku.calcFinalStock()
    },
    handleBatchSet() {
      this.detail.salePropList.batchSet(this.isEditMode)
      if (this.detail.salePropList.batchPrice) {
        this.handleChangePrice()
      }
    },
    handleRemoveProperty(idx) {
      if (!this.detail.salePropList.isPropertyEmpty(idx)) {
        this.$confirm('删除该规格类型后，当前的规格类型相关数据将丢失，确认要删除吗？\n', '提示').then(() => {
          this.detail.salePropList.removeProperty(idx)
          this.detail.salePropList.onCheckedPropValueChanged()
        })
      } else {
        this.detail.salePropList.removeProperty(idx)
        this.detail.salePropList.onCheckedPropValueChanged()
      }
    },
    handleAddProperty() {
      this.detail.salePropList.addProperty()
    },
    handleChangePropertyOption(idx) {
      this.detail.salePropList.syncPropertyIdByTitle(idx)
      this.detail.salePropList.clearValues(idx)
      this.detail.salePropList.onCheckedPropValueChanged()
    },
    handleToggleGroupTab(s, g) {
      if (s.valueList[s.selectedGroup].some(el => el.checked)) {
        this.$confirm('切换分组后，规格及其数据将被清空，确认执行此操作？', '提示').then(() => {
          s.valueList[s.selectedGroup].forEach(item => item.clear())
          CollectionUtil.removeElements(s.valueList[s.selectedGroup], el => el.valueSource === 1)
          s.selectedGroup = g.id
          this.detail.salePropList.onCheckedPropValueChanged()
        })
        return
      }
      s.selectedGroup = g.id
      this.detail.salePropList.onCheckedPropValueChanged()
    },
    handleToggleSkuChecked(sku) {
      if (!sku.value.trim()) {
        this.$message.warning('值为空不可勾选')
        return
      }
      sku.checked = !sku.checked
      this.detail.salePropList.onCheckedPropValueChanged()
    },
    handleRemoveValue(s, v) {
      s.removeProperty(v)
      this.detail.salePropList.onCheckedPropValueChanged()
    },
    handleChangePic() {
      this.detail.salePropList.onCheckedPropValueChanged()
    },
    handleChangeDeltaStock(sku) {
      sku.calcFinalStock()
    },
    handleChangeFinalStock(sku) {
      sku.calcDeltaStock()
    },
    async handleBlurValue(s, v, {value, id} = {}) {
      v.setValue(value)
      if (!value) {
        s.removeExtraEmptyProperty(v)
        this.detail.salePropList.onCheckedPropValueChanged()
      } else {
        try {
          s.assertPropertyValueNotExisted(v)
          if (!id) { // 创建id
            id = await propertyApi.selfPropertyValue(s.id, value)
            v.valueSource = 1
          }
          v.checked = true
          v.setId(id)
          s.addPropertyValueForCurrent()
          this.detail.salePropList.onCheckedPropValueChanged()
        } catch (ex) {
          this.$message.warning(ex.message)
        }
      }
    },
    handleCheckValue(s, v) {
      try {
        s.assertPropertyValueNotExisted({value: v})
      } catch (e) {
        this.$message.warning(e.message)
        return false
      }
    },
    handleSubmitUpdateSpu() {
      this.$refs.form.validate(r => {
        try {
          // 校验
          this.detail.assertIsValid()
          this.detail.salePropList.skuList.assertMaxPriceLessThan(this.formData.marketPrice)
          this.skuErrMsg = ''
        } catch (ex) {
          this.skuErrMsg = ex.message
          return
        }
        if (r) {
          this.isSubmitting = true
          spuApi.update(SpuConvertor.toSpuUpdateCmd(this.$route.query.id, this.formData, this.detail)).then(() => {
            this.$router.replace('/pdt/spu/success')
          }).finally(() => {
            this.isSubmitting = false
          })
        }
      })
    },
    handleSubmit() {
      this.$refs.form.validate(r => {
        try {
          // 校验
          this.detail.assertIsValid()
          this.detail.salePropList.skuList.assertMaxPriceLessThan(this.formData.marketPrice)
          this.skuErrMsg = ''
        } catch (ex) {
          this.skuErrMsg = ex.message
          return
        }
        if (r) {
          this.isSubmitting = true
          spuApi.create(SpuConvertor.toSpuCreateCmd(this.$route.query.categoryId, this.formData, this.detail)).then(() => {
            this.$router.replace('/pdt/spu/success')
          }).finally(() => {
            this.isSubmitting = false
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.sku_errmsg {
  color: #F56C6C;
}

.cat {
  font-size: 13px;
  background-color: #f4f4f4;
  border-radius: 4px;
  padding: 14px;

  &__item {
    &:before {
      content: ' > ';
      padding: 0 4px;
    }

    &:first-child:before {
      display: none;
    }
  }

  &__items {
    padding-left: 20px;
  }
}

.checkbox-master {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: transparent;
  z-index: 1;
  cursor: pointer;
}

.spu {

  &__color {
    width: 160px;
  }

  &__propList {
    background-color: #f7f8fa;
    color: rgba(0, 0, 0, .6);
    border-radius: 4px;
    font-size: 13px;

    &TitleArea {
      padding: 10px;
    }
  }

  &__propListContent {
    padding: 0 20px;
    padding-top: 20px;
  }

  &__salePropList {
    background-color: #f7f8fa;
    padding: 16px;
  }

  &__salePropListItems {
    padding: 0 4px;
  }

  &__salePropListItem {
    //margin-bottom: 20px;
    height: 40px;
  }

  &__propNotes {
    width: 70px;
    margin-left: 10px;
  }

  &__selfProp {
    width: 140px;
    //margin-left: 10px;
  }

  &__salePropGroupTitle {
    margin-right: 10px;
    font-size: 13px;

    &Tip {
      color: #999;
      font-size: 12px;
    }
  }

  &__salePropGroup {
    padding: 10px;
    background-color: #fff;
    margin-top: 10px;

    &:first-child {
      margin-top: 0;
    }
  }

  &__tabs {
    border-collapse: collapse;
    padding: 10px 0;
  }

  &__tab {
    border: 1px solid #eee;
    font-size: 12px;
    width: 70px;
    text-align: center;

    cursor: pointer;

    &--selected {
      color: #4b97de;
      border-color: #4b97de;
    }

    &:first-child {
      border-top-left-radius: 6px;
      border-bottom-left-radius: 6px;
    }

    &:last-child {
      border-top-right-radius: 6px;
      border-bottom-right-radius: 6px;
    }
  }
}

.box {
  border: 1px solid #eee;
  margin-top: 20px;
  padding: 20px;

  &__content {
  }

  &__title {
    font-weight: bold;
    padding-bottom: 20px;

    span {
      color: #4b97de;
      margin-right: 10px;

    }
  }
}

.tip {
  font-size: 12px;
  color: #999;
}

.spu__prop-table {
  border-collapse: collapse;
  background-color: #fff;
  table-layout: fixed;
  width: 100%;
  font-size: 13px;

  th {
    border: 1px solid #eee;
    background-color: rgb(240, 242, 245);
    padding: 10px;
    font-weight: normal;
    text-align: left;
  }

  td {
    border: 1px solid #eee;
    padding: 10px 10px;
  }
}

.spu__prop-value--required {
  &:before {
    content: '*';
    color: red;
  }
}

.summary {
  font-size: 12px;
  padding: 10px 0 0 0;

  &__item {
    & + .summary__item {
      margin-left: 30px;
    }
  }

  &__label {
    padding-right: 10px;
  }

  &__value {
    color: #999;
  }
}

.delta-stock-td {
  position: relative;
}

.delta-stock {
  ::v-deep input {
    padding-left: 50px !important;
  }
}

.delta-stock-flag {
  position: absolute;
  left: 6px;
  top: 50%;
  display: flex;
  font-size: 12px;
  transform: translateY(-50%);
  align-items: center;
  z-index: 100;

  &__item {
    cursor: pointer;
    border: 1px solid #999;
    width: 20px;
    height: 20px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    color: #999;

    &--selected {
      color: #4b97de;
      border: 1px solid #4b97de;
    }
  }
}

::v-deep .el-input__inner {
  padding-right: 10px !important;
  padding-left: 10px !important;
}

</style>
